/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.example.netcracker.ui;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import ru.example.netcracker.controller.ControllerFacade;
import ru.example.netcracker.model.entity.Alarm;
import ru.example.netcracker.model.entity.Notification;
import ru.example.netcracker.model.entity.Task;


/**
 *
 * @author Nikolay
 */
public class CreateTaskDialog extends javax.swing.JDialog {

    public static CreateTaskDialog newInstance(java.awt.Frame parent, ControllerFacade ctrl) {
        return new CreateTaskDialog(parent, ctrl);
    }
    
    private class Mp3Filter extends FileFilter {

        @Override
        public boolean accept(File file) {
            return file.isDirectory() || file.getAbsolutePath().endsWith(".mp3");
        }

        @Override
        public String getDescription() {
            return "Аудио файлы (*.mp3)";
        }
    }
    
    private final ControllerFacade ctrl;    
    private Task task;
    
    public CreateTaskDialog(java.awt.Frame parent, ControllerFacade ctrl) {
        super(parent, true);
        this.ctrl = ctrl;
        initComponents();
    }
    
    public Task getTask() {
        return task;
    }

    public void setTask(Task task) {
        this.task = task;
        timeSpinner.setValue(task.getDate());
        dateSpinner.setValue(task.getDate());
        titleField.setText(task.getName());
        jTabbedPane1.setEnabled(false);
        if(task instanceof Notification) {
            jTabbedPane1.setSelectedIndex(0);            
            descriptionText.setText(((Notification) task).getDescription());
            createNotificationButton.setText("Изменить");
            return;
        }
        if(task instanceof Alarm) {
            jTabbedPane1.setSelectedIndex(1);
            pathText.setText(((Alarm) task).getPath());
            createAlarmButton.setText("Изменить");
        }
    }
    
    private Date createDate() throws ParseException {        
        Date date = (Date) dateSpinner.getValue();
        Date time = (Date) timeSpinner.getValue();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss dd.MMMM.yyyy");
        String formatDate = format.format(date);
        String[] split = formatDate.split(" ");        
        String dateStr = split[1];
        formatDate = format.format(time);
        split = formatDate.split(" ");
        String timeStr = split[0];
        String newDate = timeStr + " " + dateStr;
        return format.parse(newDate);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        titleField = new javax.swing.JTextField();
        dateSpinner = new javax.swing.JSpinner();
        timeSpinner = new javax.swing.JSpinner();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        descriptionText = new javax.swing.JTextArea();
        createNotificationButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        selectMp3Button = new javax.swing.JButton();
        createAlarmButton = new javax.swing.JButton();
        pathText = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Тема");

        titleField.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N

        dateSpinner.setFont(new java.awt.Font("Times New Roman", 0, 36)); // NOI18N
        dateSpinner.setModel(new javax.swing.SpinnerDateModel());
        dateSpinner.setEditor(new javax.swing.JSpinner.DateEditor(dateSpinner, "dd MMMM yyyy"));

        timeSpinner.setFont(new java.awt.Font("Times New Roman", 0, 72)); // NOI18N
        timeSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
        timeSpinner.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        timeSpinner.setEditor(new javax.swing.JSpinner.DateEditor(timeSpinner, "HH:mm:ss"));

        jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Описание");

        descriptionText.setColumns(20);
        descriptionText.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        descriptionText.setRows(5);
        descriptionText.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        jScrollPane1.setViewportView(descriptionText);

        createNotificationButton.setText("Создать");
        createNotificationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createNotificationButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(createNotificationButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(createNotificationButton)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Оповещение", jPanel1);

        selectMp3Button.setText("Выбрать звук...");
        selectMp3Button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectMp3ButtonActionPerformed(evt);
            }
        });

        createAlarmButton.setText("Создать");
        createAlarmButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createAlarmButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(createAlarmButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(selectMp3Button)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pathText, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selectMp3Button)
                    .addComponent(pathText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 238, Short.MAX_VALUE)
                .addComponent(createAlarmButton)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Будильник", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane1)
                    .addComponent(timeSpinner, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dateSpinner, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(titleField, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(timeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(titleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createNotificationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createNotificationButtonActionPerformed
        String title = titleField.getText();
        String description = descriptionText.getText();
        Date date;
        try {
            date = createDate();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, ex, "Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if(date.getTime() - System.currentTimeMillis() <= 0) {
            JOptionPane.showMessageDialog(this, "Введенная дата раньше текущей", "Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (task != null && (task instanceof Notification)) {
            ctrl.updateNotification(task.getId(), title, description, date, null);                       
        } else {
            ctrl.createNotification(title, description, date); 
        }
        dispose();
    }//GEN-LAST:event_createNotificationButtonActionPerformed

    private void selectMp3ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectMp3ButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        
        fc.setFileFilter(new Mp3Filter());
        if(fc.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
            return;
        
        File file = fc.getSelectedFile();
        pathText.setText(file.getAbsolutePath());
    }//GEN-LAST:event_selectMp3ButtonActionPerformed

    private void createAlarmButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createAlarmButtonActionPerformed
        String title = titleField.getText();
        String path = pathText.getText();
        Date date = null;
        try {
            date = createDate();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, ex, "Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if(date.getTime() - System.currentTimeMillis() <= 0) {
            JOptionPane.showMessageDialog(this, "Введенная дата раньше текущей", "Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (task != null && (task instanceof Alarm)) {
            ctrl.updateAlarm(task.getId(), title, path, date);                       
        } else {
            ctrl.createAlarm(title, path, date); 
        }
        dispose();
    }//GEN-LAST:event_createAlarmButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createAlarmButton;
    private javax.swing.JButton createNotificationButton;
    private javax.swing.JSpinner dateSpinner;
    private javax.swing.JTextArea descriptionText;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField pathText;
    private javax.swing.JButton selectMp3Button;
    private javax.swing.JSpinner timeSpinner;
    private javax.swing.JTextField titleField;
    // End of variables declaration//GEN-END:variables
}
